package org.ikross.h2.wkb;

import java.io.IOException;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKBReader;
import com.vividsolutions.jts.io.WKBWriter;
import com.vividsolutions.jts.io.WKTReader;

public class WKBUtil {
	private WKBUtil(){
		//Para evitar instancias de esta clase
	}
	
	private static WKBReader wkbReader=null;
	private static WKBWriter wkbWriter=null;
	
	private static WKTReader wktReader=null;
	
	private static WKBReader getWKBReaderInstance(){
		if(wkbReader==null){
			wkbReader=new WKBReader();
		}
		return wkbReader;
	}
	
	private static WKBWriter getWKBWriterInstance(){
		if(wkbWriter==null){
			wkbWriter=new WKBWriter();
		}
		return wkbWriter;
	}
	
	private static WKTReader getWKTReaderInstance(){
		if(wktReader==null){
			wktReader=new WKTReader();
		}
		return wktReader;
	}

	public static byte[] serialize(Geometry geometry) throws IOException{
		//return WKBEncoder.encodeGeometry(geometry);
		return getWKBWriterInstance().write(geometry);
	}
	
	public static Geometry unserialize(byte[] serializedGeometry) throws ParseException, IOException{
		//return WKBReader.read(serializedGeometry);
		return getWKBReaderInstance().read(serializedGeometry);
	}
	
	public static Geometry geometryFromText(String wellKnownText) throws ParseException{
		return getWKTReaderInstance().read(wellKnownText);
	}
	
	/*public static void main(String args[]){
		try{
			Class.forName("org.h2.Driver");
			Connection con=DriverManager.getConnection("jdbc:h2:tcp://localhost/default", "sa", "");
			Statement st=con.createStatement();
			ResultSet rs=st.executeQuery("SELECT GEOM FROM EjesLinSHP");
			
			ArrayList array=new ArrayList();
			while(rs.next()){
				array.add(rs.getBytes(1));
			}
			
			long tiempo=0;
			long ini;
			Iterator iter;
			for (int i = 0; i < 10; i++) {
				iter=array.iterator();
				while(iter.hasNext()){
					ini=System.currentTimeMillis();
					WKBUtil.unserialize((byte[])iter.next());
					tiempo+=System.currentTimeMillis()-ini;
				}
			}
			
			System.out.println("Tiempo total WKBUtil: "+tiempo+" msg");
			
			WKBParser2 parser=new WKBParser2();
			for (int i = 0; i < 10; i++) {
				iter=array.iterator();
				while(iter.hasNext()){
					ini=System.currentTimeMillis();
					parser.parse((byte[])iter.next());
					tiempo+=System.currentTimeMillis()-ini;
				}
			}
			
			System.out.println("Tiempo total WKBParser2: "+tiempo+" msg");
		}
		catch(Exception except){
			System.out.println(except);
		}
	}*/
}